<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="/static/js/head.js"></script>
<link rel="stylesheet" type="text/css" href="/static/css/contractList.css" />
</head> 
<body id="layout" class="easyui-layout">
	<div data-options="region:'center',border:false">
		<table id="infoDrid"></table>
	</div>
<!-- 查询条件 -->
<div  style="width:250px;padding:5px;display: none;">
<form id="searchForm">
	<table class="searchTable">
		<tr>
			<td class="searchLeft">合同名称：</td>
			<td class="searchRight">
				<input class="easyui-validatebox" name="username" id="usernameSearch">
			</td>
		</tr>
		<tr>
			<td  class="searchLeft">合同编号：</td>
			<td class="searchRight">
				<input class="easyui-validatebox" name="loginname" id="loginnameSearch" value=''>
				<input id="signdate" type="hidden" value="">
			</td>
		</tr>
		<tr>
			<td class="searchLeft">开始时间：</td>
			<td class="searchRight">
				<input class="easyui-datetimebox" name="stattime" id="stattimeSearch">
			</td>
		</tr>
		<tr>
			<td  class="searchLeft">结束时间：</td>
			<td class="searchRight">
				<input class="easyui-datetimebox" name="endtime" id="endtimeSearch">
			</td>
		</tr>
	</table>
	<div>
	<a id="searchbtn" class="easyui-linkbutton" data-options="iconCls:'icon-ccSearch'" style="margin-left:50px">查询</a>
	<a id="resetbtn"   class="easyui-linkbutton" data-options="iconCls:'icon-ccReload'">重置</a>
	</div>
</form>
</div>
	<!-- dataGrid工具栏 -->
	<div id="toolbar">
		<!-- <a id="search" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ccSearch',plain:true" >查询</a> -->
		<a id="uploadBTN" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ccOut',plain:true" >上传</a>
		<a id="checkFile" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-accolist',plain:true" >查看附件</a>
		<a id="downLoadFile" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ccDownload',plain:true" >下载全部附件</a>
		<a id="edit" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ccEdit',plain:true" >编辑合同</a>
		<a id="finish" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-lock',plain:true" >结束合同</a>
		<a id="delete" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:true" >删除合同</a>
	</div>
	
	<!-- 编辑合同订单 -->
	<div id="editDialog">
		<form id="editForm">
			<table class="tableForm">
				<tr>
					<td class="formLeft">合同区域:</td>
					<td>
						<input class="easyui-validatebox" data-options="required:true" name="region" id="region">
						<input type="text" id="contractID" style="display: none;">
					</td>
				</tr>
				<tr>
					<td class="formLeft">甲方名称:</td>
					<td>
						<select class="easyui-combobox" name="firstPartyName" id="firstPartyName" placeholder="请输入甲方名称" style="width:170px;">
						    <option value="移动">移动</option>
						    <option value="联通">联通</option>
						    <option value="电信">电信</option>
						    <option value="铁塔">铁塔</option>
						    <option value="省通建">省通建</option>
						    <option value="广电">广电</option>
						    <option value="其他">其他</option>
						</select>
					</td>
				</tr>
				<tr>
					<td class="formLeft">中标单位:</td>
					<td>
						<input class="easyui-validatebox" name="secondPartyName" id="secondPartyName">
					</td>
				</tr>
				<tr>
					<td class="formLeft">合同编号:</td>
					<td>
						<input class="easyui-validatebox" name="contractNo" id="contractNo">
					</td>
				</tr>
				<tr>
					<td class="formLeft">合同名称:</td>
					<td>
						<input class="easyui-validatebox" name="contractName" id="contractName">
					</td>
				</tr>
				<tr>
					<td class="formLeft">合同金额:</td>
					<td>
						<input class="easyui-numberbox" data-options="min:0" name="contractAmount" id="contractAmount">
					</td>
				</tr>
				<tr>
					<td class="formLeft">签订时间:</td>
					<td>
						<input class="easyui-datebox" name="signTime" id="signTime">
					</td>
				</tr>
				<tr>
					<td class="formLeft">开始时间:</td>
					<td>
						<input class="easyui-datebox" name="startTime" id="startTime">
					</td>
				</tr>
			</table>
		</form>
	</div>
	<!-- 上传 -->
	<div id="uploadDialog">
		<form id="uploadForm" enctype="multipart/form-data" method="post" accept-charset="UTF-8" >
			<table class="tableForm">
				<tr>
					<td><label>上传类型</label></td>
					<td>
						<label><input type="radio" name="certType"
			              checked="checked" value="1">中标通知书</label>
			            <label><input type="radio" name="certType"
			              value="2">框架合同压缩文件</label>
			            <input type="text" id="uploadContractID" style="display: none;">
					</td>
				</tr>
				<tr id="inputCB1" >
					<td><label>选择文件</label></td>
					<td>
						<input id="miData" type="text">
						<a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-upload',plain:true"
							onClick="document.getElementById('file').click()"></a>
						<input type="file" style="width:300px" id="file" name="file" class="filePrew" onchange="change_photo();">
					</td>
				</tr>
				<tr id="inputCB4" >
					<td ><label>图片预览</label></td>
					<td>
						<div id="Imgdiv">
						</div>
					</td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

<script>
	$(function(){
		$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
		//页面初始化
		layoutLoad();
		//数据表格加载
		gridLoad(1,15);	
		//loadAndSetGridData();	
		//点击事件
		clickFunction();

	});
	//页面初始化
	function layoutLoad(){
//		$('#layout').layout('collapse','east');
		//信息编辑dialog
		$('#editDialog').dialog({
			title: '编辑合同订单',
		    width: 340,
		    height:340,
		    closed: true,    
		    modal: true,
		    buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					editInfo();//添加信息
                }
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#editDialog').dialog('close');
				}
			}], 
		});
		//信息编辑dialog
		$('#uploadForm').dialog({
			title: '上传',
		    width: 500,
		    height:500,
		    closed: true,    
		    modal: true,
		    buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					uploadFiles()
                }
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#uploadForm').dialog('close');
				}
			}], 
		});
	}
	//数据表格加载
	function gridLoad(pageNumber,pageSize) {
		$.ajax({
			url : getHost() + '/contract/list/pageable/adapter/order_by_create_time_desc',
			type : "GET",
			data : {
				"pageNumber": pageNumber,
			    "pageSize": pageSize,
			},
			async : false,
			dataType : "json",
			contentType: 'application/json;charset=UTF-8',
			success : function(data) {
				if (data.code==200&&typeof(data.data) == "object") {
					var width = $('#infoDrid').parent().width();
					var height = $('#infoDrid').parent().height();
					$('#infoDrid').datagrid({
						toolbar : "#toolbar",
						data: data.data.page.rows,
						width : width,
						height : height,
						async : false,
						fit : true,
						border : false,
						singleSelect : true,
						fitColumns : true,
						striped : true,
						pagination : true,
						scrollbarSize:0 ,
						columns : [ [
							{field:'region',title:'合同区域',align:'center'},
							{field:'firstPartyName',title:'甲方名称',align:'center'},
							{field:'secondPartyName',title:'中标单位',align:'center'},
							{field:'contractNo',title:'合同编号',align:'center'},
							{field:'contractName',title:'合同名称',align:'center'},
							{field:'contractAmount',title:'合同金额(元)',align:'center'},
							{field:'status',title:'合同状态',align:'center',
								formatter: function(value,row,index){
									if(value=="2"){
										return "已结束";
									}else if(value=="1"){
										return "未结束";
									}else{
										return "";
									}
								}
							},
							{field:'signTime',title:'签订时间',align:'center'},
							{field:'startTime',title:'开始时间',align:'center'},
							{field:'endTime',title:'结束时间',align:'center'},
							{field:'createUser',title:'创建人',align:'center',
								formatter: function(value,row,index){
									return value.nickname;
								}
							},
							{field:'createTime',title:'创建时间',align:'center'},
							{field:'id',title:'操作',align:'center' ,
								formatter: function(value,row,index){
									return "<input style=\"cursor:pointer;\" type=\"button\" value=\"订单列表\" onClick=\"orderList(" + index + ")\" style=\"width:100px\"/>";
								}
							}
						] ],
					});
					var p = $('#infoDrid').datagrid('getPager');
			        $(p).pagination({
			        	total : data.data.page.total,
			            pageSize: pageSize,
			            pageList: [15, 30, 50],
			            pageNumber : pageNumber,
			            beforePageText: '第',
			            afterPageText: '页    共 {pages} 页',
			            displayMsg: '当前显示 {from}-{to} 条记录,共 {total} 条记录',
			            showRefresh : false,
			            onSelectPage:function(pageNumber, pageSize){
			        		gridLoad(pageNumber,pageSize);
			        	}
			        });
				}else{
					$.messager.alert("提示",data.message);
				}
			}
		});
	}
	//点击事件
	function clickFunction() {
		$('#search').click(function() {
			$('#layout').layout('expand', 'east');
		});
		//点击查询
		$('#searchbtn').click(function() {
			gridLoad(1,15);
		});
		$('#resetbtn').click(function() {
			$('#searchForm')[0].reset();
			$("#loginnameSearch").val('');
			$("#signdate").val('');
			$('#stattimeSearch').datetimebox('setValue', '');
			$('#endtimeSearch').datetimebox('setValue', '');
			gridLoad(1,15);
		});

		//编辑点击事件
		$('#edit').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			$('#editForm')[0].reset();
			$("#contractID").val(row.id);
			$('#editForm').form('load',row);
			$('#editDialog').dialog('open');
		});
		
		//上传 
		$('#uploadBTN').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			$('#uploadForm')[0].reset();
			$("#uploadContractID").val(row.id);
			$('#uploadForm').dialog('open');
		});
		//查看附件
		$('#checkFile').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			sessionStorage.setItem('fileType','1');
			sessionStorage.setItem('row',JSON.stringify(row));
			parent.addTab('附件展示',  "/accessories.html");
		});
		//删除 
		$('#delete').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			$.messager.confirm('提示','确定要删除该合同吗? <br/>'+row.contractName,function(r){
			    if (r){
			    	$.ajax({
						url:getHost() + '/contract/' + row.id,
						type:'delete',
						error:function(){
							$.messager.alert("提示","数据操作存在异常!");
						},
						contentType: 'application/json;charset=UTF-8',
						async : false,
						dataType : "json",
						success:function(data){
							if(data.code==200){
								$.messager.alert("提示","删除成功");
								gridLoad(1,15);
							}else{
								$.messager.alert("提示",data.message);
							}
						}
					});
			    }
			});
		});
		//结束合同
		$('#finish').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			$.messager.confirm('提示','确定要结束吗?',function(r){
			    if (r){
			    	$.ajax({
						url:getHost() + '/contract/end?contractId=' + row.id,
						type:'GET',
						error:function(){
							$.messager.alert("提示","数据操作存在异常!");
						},
						contentType: 'application/json;charset=UTF-8',
						success:function(data){
							if(data.code==200){
								$.messager.alert("提示","结束合同成功");
								gridLoad(1,15);
							}else{
								$.messager.alert("提示",data.message);
							}
						}
					});
			    }
			});
		});
		//打包下载
		$('#downLoadFile').click(function() {
			var row = $('#infoDrid').datagrid('getSelected');
			if(row==null){
				$.messager.alert("提示","请选中一行!");
				return;
			}
			$.messager.confirm('提示','确定要下载选中合同下所有附件吗?',function(r){
			    if (r){
			    	window.location.href=getHost() + '/contract/zip_download/' + row.id;
			    }
			});
		});
		
	}
	
	//查看合同订单列表 
	function orderList(index){
		var rows = $('#infoDrid').datagrid('getRows');//获得所有行
        var row = rows[index];//根据index获得其中一行。
		sessionStorage.setItem('contractId',row.id);
		sessionStorage.setItem('contractName',row.contractName);
		parent.addTab('订单列表',  "/orderList.html")
	}
	
	//修改
	function editInfo(){
		if($("#editForm").form('validate')){
			var row = $('#infoDrid').datagrid('getSelected');
			var letterOfAcceptance = "",contractAttachment = "";
				//contractAttachment = row.contractAttachment.id;
				//letterOfAcceptance = row.letterOfAcceptance.id;
			$.ajax({
				url:getHost() + '/contract',
				type:'PUT',
				data:JSON.stringify({
					region : $("#region").val(),
					firstPartyName : $('#firstPartyName').combobox('getValue'),
					secondPartyName : $("#secondPartyName").val(),
					contractNo : $("#contractNo").val(),
					contractName : $("#contractName").val(),
					contractAmount : $("#contractAmount").val(),
					signTime : $("#signTime").val(),
					startTime : $("#startTime").val(),
					id : $("#contractID").val(),
					//letterOfAcceptance : letterOfAcceptance,
					//contractAttachment :contractAttachment,
				}),
				dataType : "json",
				contentType: 'application/json;charset=UTF-8',
				error : function(XMLHttpRequest, textStatus, errorThrown){
					$.messager.alert("提示","数据操作存在异常!");
				},
				beforeSend: function(xhr) {
	                xhr.withCredentials = true;
	            },
	            crossDomain:true,
				success:function(data){
					if(data.code=="200"&&data.data.item.id>0){
						$.messager.alert("提示","保存成功");
						$('#editForm').form('clear');
						$('#editDialog').dialog('close');
						gridLoad(1,15);
					}else{
						$.messager.alert("提示",data.message);
					}
				}
			});
		}
	}
	function uploadFiles(){
 	    var count = 0;
	    var ids = "";
    	var files = document.getElementById("file").files;
    	var fl = files.length;
		for(var i=0; i< fl; i++){
			var fileObj = document.getElementById("file").files[i];
			var formFile = new FormData();
            formFile.append("file", fileObj); //加入文件对象
			$.ajax({
				url:getHost() + '/file',
				type : 'post',
                data: formFile,
				error : function(data) {
					$.messager.alert('提示', "第"+i+"张"+'上传失败！');
				},
				contentType : false,
				processData : false,
				async : false,
				success : function(data) {
					if(data.code=="200"&&data.data.item.id>0){
						ids+=data.data.item.id;
						count+=1;
					}else{
						$.messager.alert("提示","第"+i+"张"+data.message);
					}
				}
			});
		}
		if(count==fl){
			var row = $('#infoDrid').datagrid('getSelected');
			var letterOfAcceptance = "",contractAttachment = "";
			if($("input[name='certType']:checked").val()==1){
				letterOfAcceptance = ids;
				if(typeof(row.contractAttachment) == "object"){
					contractAttachment = row.contractAttachment.id;
				}
			}else if($("input[name='certType']:checked").val()==2){
				contractAttachment = ids;
				if(typeof(row.letterOfAcceptance) == "object"){
					letterOfAcceptance = row.letterOfAcceptance.id;
				}
			}
			$.ajax({
				url:getHost() + '/contract',
				type:'PUT',
				data:JSON.stringify({
					region : row.region,
					firstPartyName : row.firstPartyName,
					secondPartyName : row.secondPartyName,
					contractNo : row.contractNo,
					contractName : row.contractName,
					signTime : row.signTime,
					startTime : row.startTime,
					id : row.id,
					letterOfAcceptance : letterOfAcceptance,
					contractAttachment :contractAttachment,
				}),
				dataType : "json",
				contentType: 'application/json;charset=UTF-8',
				error : function(XMLHttpRequest, textStatus, errorThrown){
					$.messager.alert("提示","数据操作存在异常!");
				},
				beforeSend: function(xhr) {
	                xhr.withCredentials = true;
	            },
	            crossDomain:true,
				success:function(data){
					if(data.code=="200"&&data.data.item.id>0){
						$.messager.alert("提示","上传成功");
						$('#uploadForm').form('clear');
						$("#Imgdiv").html("");
						gridLoad(1,15);
						$('#uploadForm').dialog('close');
					}else{
						$.messager.alert("提示",data.message);
					}
				}
			});
		}
	}
	function change_photo(){
		$("#Imgdiv").html("");
		var files = document.getElementById("file").files;
		var names = "";
		for(var i=0; i< files.length; i++){
			names += files[i].name+",";
		}
		//alert(names);
		$("#miData").val(names.substring(0,names.length));
	    PreviewImage($("input[id='file']")[0]);
	}
	function PreviewImage(fileObj){
	    var allowExtention=".jpg,.bmp,.gif,.png,.zip,.rar,.jpeg";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;  
	    var browserVersion= window.navigator.userAgent.toUpperCase();
	    //循环判断后缀名
	    for(i=0;i<fileObj.files.length;i++){
	    	var extention=fileObj.files[i].name.substring(fileObj.files[i].name.lastIndexOf("."),fileObj.files[i].name.length).toLowerCase();
	    	if(allowExtention.indexOf(extention)<0){
	    		$.messager.alert("仅支持"+allowExtention+"为后缀名的文件!");  
	   	        fileObj.value="";//清空选中文件  
	   	        if(browserVersion.indexOf("MSIE")>-1){
	   	            fileObj.select();  
	   	            document.selection.clear();  
	   	        }                  
	   	        fileObj.outerHTML=fileObj.outerHTML;
	   	        return false;
	    	}
	    }
	    
	    $.each(fileObj.files,function(key,value){
	        //每次都只会遍历一个图片数据
	        var div = document.createElement("div");
	        var img = document.createElement("img");
	        div.className = "pic";
	        img.width="200";
	        img.height="200";

	        var fr = new FileReader();
	        fr.onload = function(){
	        	if(this.result.substring(5,this.result.indexOf("/"))=="image"){
		            img.src=this.result;
	        	}else{
	        		img.src="/static/images/compress.jpg";
	        	}
	            div.appendChild(img);
	            document.getElementById("Imgdiv").appendChild(div);
	        }
	        fr.readAsDataURL(value);
	    })
	}
	function getID(con){
		con = JSON.parse(con);
		var str = "";
		for(i=0;i<con.length;i++){
			str += con[i].id + ",";
		}
		return "["+str.substring(0,str.length-1)+"]";
	}
</script>